<template>
  <div class="app-container" :key="tableKey">
    <header>
      <ul>
        <li style="width: 70%">
          <div class="title">
            <span class="title-left"
              >{{ resultInfo.taskName }}迁移任务汇总：</span
            >
            <span class="title-right" v-if="resultInfo.taskType"
              >{{ resultInfo.taskType.split("-")[0]
              }}<i class="el-icon-right" style="margin: 0 10px" />{{
                resultInfo.taskType.split("-")[1]
              }}</span
            >
          </div>
          <div class="subTitle">
            <span class="subTitle-left">耗时：</span>
            <span class="subTitle-right">
              {{ resultInfo.startTime }} 至 {{ resultInfo.endTime }}</span
            >
          </div>
        </li>
        <li style="width: 28%">
          <div class="successRateText">成功率：</div>
          <el-progress
            color="#67C23A"
            :stroke-width="20"
            text-inside
            :percentage="
              resultInfo.successRate == 'NaN'
                ? 0
                : Number(resultInfo.successRate)
            "
          />
        </li>
      </ul>
    </header>
    <main>
      <el-table
        border
        :data="tableData"
        style="width: 100%"
        height="70vh"
        stripe
        :row-style="{ height: '55px' }"
      >
        <el-table-column prop="typeName" align="center" label="迁移对象">
          <template slot-scope="scope">
            <div
              class="text"
              v-for="dict in dict.type.transfer_result_object_type"
              :key="dict.value"
            >
              {{ dict.value == scope.row.typeName ? dict.label : "" }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="total" label="总数" align="center">
          <template slot-scope="scope">
            <div class="text">
              {{ scope.row.total }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="completes" label="成功数" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              :class="[
                scope.row.completes > 0 ? 'successText' : 'successThanText',
              ]"
              @click="clickOpenSuccessDrawer(scope.row)"
              >{{ scope.row.completes }}</el-button
            >
          </template>
        </el-table-column>
        <el-table-column prop="failtures" label="失败数" align="center">
          <template slot-scope="scope">
            <el-badge
              v-if="scope.row.failtures > 0 && scope.row.errorTipsCount > 0"
              :value="scope.row.errorTipsCount"
              class="failBadge"
            >
              <el-button
                type="text"
                size="small"
                @click="clickOpenSuccessDrawer(scope.row, 'fail')"
                :class="[scope.row.failtures > 0 ? 'failText' : 'failThanText']"
                >{{ scope.row.failtures }}</el-button
              >
            </el-badge>
            <el-button
              v-else
              type="text"
              size="small"
              @click="clickOpenSuccessDrawer(scope.row, 'fail')"
              :class="[scope.row.failtures > 0 ? 'failText' : 'failThanText']"
              >{{ scope.row.failtures }}</el-button
            >
          </template>
        </el-table-column>
        <el-table-column prop="successRate" label="成功率" align="center">
          <template slot-scope="scope">
            <div class="text">{{ scope.row.successRate }}</div>
          </template>
        </el-table-column>
      </el-table>
    </main>
    <el-drawer
      size="50%"
      :title="title"
      :visible.sync="successDrawer"
      direction="rtl"
      :before-close="handleClose"
    >
      <div class="tableBox" v-if="pagedData">
        <div class="search">
          <el-input
            style="width: 30%; margin-right: 10px"
            v-model="searchInput"
            placeholder="请输入对象名称"
          ></el-input>
          <el-button
            type="success"
            icon="el-icon-search"
            @click="searchSuccessTable"
            >搜索</el-button
          >
        </div>
        <el-table
          border
          :data="pagedData"
          style="width: 100%"
          height="75vh"
          stripe
          :row-style="{ fontSize: '14px', height: 'calc(75vh / 11)' }"
        >
          <el-table-column align="center" label="序号">
            <template slot-scope="scope">
              <div v-text="getIndex(scope.$index)"></div>
            </template>
          </el-table-column>
          <el-table-column
            prop="sourceObjectName"
            align="center"
            label="对象名称"
          >
            <template slot-scope="scope">
              <el-popover
                v-if="!type"
                placement="right"
                width="600"
                trigger="click"
                popper-class="popoverEditor"
              >
                <editor
                  :key="codeHeight"
                  @init="editorInit"
                  ref="aceEditor"
                  v-model="successSql"
                  width="100%"
                  :height="codeHeight"
                  lang="sql"
                  theme="dracula"
                  :options="{
                    enableBasicAutocompletion: true,
                    enableSnippets: true,
                    enableLiveAutocompletion: true,
                    showPrintMargin: false, //去除编辑器里的竖线
                    fontSize: 16,
                    readOnly: true,
                  }"
                ></editor>
                <el-button
                  slot="reference"
                  @click="handleSuccessCode(scope.row)"
                  type="text"
                  class="objName"
                  >{{ scope.row.sourceObjectName }}</el-button
                >
              </el-popover>

              <el-popover
                v-if="type && scope.row.errorTips"
                placement="top"
                :key="type"
                width="600"
                trigger="hover"
              >
                <pre class="errTips">{{ scope.row.errorTips }}</pre>
                <el-badge
                  value="?"
                  type="warning"
                  class="failBadge"
                  slot="reference"
                >
                  <div class="text">{{ scope.row.sourceObjectName }}</div>
                </el-badge>
              </el-popover>
              <div class="text" v-if="type && !scope.row.errorTips">
                {{ scope.row.sourceObjectName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="完成时间">
            <template slot-scope="scope">
              <div>{{ scope.row.endTime }}</div>
            </template>
          </el-table-column>

          <el-table-column align="center" label="操作" v-if="type">
            <template slot-scope="scope">
              <el-button
                size="mini"
                class="text"
                type="text"
                @click="chatRepair(scope.row)"
                >AI智能修复</el-button
              >
              <el-button
                size="mini"
                class="text"
                type="text"
                @click="clickOpenObjDetail(scope.row)"
                >查看详情</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <div class="paginationBox">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="pageNum"
            :page-size="pageSize"
            layout="total,prev, pager, next, jumper"
            :total="total"
            v-if="total > 10"
          />
        </div>
      </div>
    </el-drawer>

    <el-drawer
      :size="outsideItem.sourceDdl ? '100%' : '50%'"
      title="对象详情"
      :visible.sync="objDetailDrawer"
      direction="rtl"
      :before-close="handleObjDetailClose"
    >
      <div
        class="info"
      >
        <div class="source" v-if="outsideItem.sourceDdl">
          <h3>源表-基本信息</h3>
          <div class="sourceTable">
            <div>
              <p>对象名称</p>
              <p>{{ outsideItem.sourceObjectName }}</p>
            </div>
            <div>
              <p>对象类型</p>
              <p>{{ outsideItem.type }}</p>
            </div>
            <div>
              <el-button
                type="primary"
                icon="el-icon-document-copy"
                size="small"
                @click="copyDdl(outsideItem.sourceDdl)"
                >复制</el-button
              >
            </div>
          </div>
          <div style="margin-top: 20px">
            <editor
              :key="codeHeight"
              @init="editorInit"
              ref="aceEditor"
              v-model="outsideItem.sourceDdl"
              width="100%"
              :height="400"
              lang="sql"
              theme="dracula"
              :options="{
                enableBasicAutocompletion: true,
                enableSnippets: true,
                enableLiveAutocompletion: true,
                showPrintMargin: false, //去除编辑器里的竖线
                fontSize: 16,
              }"
            ></editor>
          </div>
        </div>
        <div class="convert" v-if="outsideItem.sourceDdl">
          <div class="convert-main">
            <el-button
              icon="el-icon-right"
              type="success"
              @click="handleConvert"
              >转换</el-button
            >
          </div>
        </div>
        <div :class="{ sink: true, delStructure: !outsideItem.sourceDdl }">
          <h3>目标表-基本信息</h3>
          <div class="sinkTable">
            <div>
              <p>对象名称</p>
              <p>{{ outsideItem.sinkObjectName }}</p>
            </div>
            <div>
              <p>对象类型</p>
              <p>{{ outsideItem.type }}</p>
            </div>
            <div>
              <el-button
                type="primary"
                icon="el-icon-document-copy"
                size="small"
                @click="copyDdl(outsideItem.sinkDdl)"
                >复制</el-button
              >
              <el-button
                type="primary"
                icon="el-icon-circle-check"
                size="small"
                @click="handleSuccess"
                >置为成功并保存</el-button
              >
              <el-button
                type="success"
                icon="el-icon-video-play"
                size="small"
                @click="executeSql"
                >执行</el-button
              >
              <el-popover
                v-if="outsideItem.message"
                placement="top"
                :key="outsideItem.message"
                width="600"
                trigger="click"
                style="margin: 0 10px"
              >
                <pre class="errTips">{{ outsideItem.message }}</pre>
                <el-button
                  slot="reference"
                  type="danger"
                  icon="el-icon-warning-outline"
                  size="small"
                  >错误信息</el-button
                >
              </el-popover>

              <el-button
                type="danger"
                icon="el-icon-warning-outline"
                size="small"
                @click="dialogStackVisible = true"
                >堆栈错误信息</el-button
              >
            </div>
          </div>
          <div style="margin-top: 20px">
            <editor
              :key="codeHeight"
              @init="editorInit"
              ref="aceEditor"
              v-model="outsideItem.sinkDdl"
              width="100%"
              :height="400"
              lang="sql"
              theme="dracula"
              :options="{
                enableBasicAutocompletion: true,
                enableSnippets: true,
                enableLiveAutocompletion: true,
                showPrintMargin: false, //去除编辑器里的竖线
                fontSize: 16,
              }"
            ></editor>
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- <iframe src="http://192.168.0.108/" frameborder="0"></iframe> -->

    <el-dialog
      title="堆栈错误信息"
      :visible.sync="dialogStackVisible"
      width="75%"
    >
      <pre><code>{{ outsideItem.errors }}</code></pre>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogStackVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getJobResult } from "@/api/console/dataTaskLog";
import { getDataTaskconf } from "@/api/console/dataTaskconf.js";
import { sqlTaskExecuteSql } from "@/api/console/executeSql";
import {
  dataReportObjectEdit,
  sqlTaskConvertSql,
} from "@/api/console/dataTaskLog";

export default {
  dicts: ["transfer_result_object_type"],
  components: { editor: require("vue2-ace-editor") },
  data() {
    return {
      NextdataDialog: false,
      dialogStackVisible: false,
      objDetailDrawer: false,
      successSql: "",
      successTableData: [],
      pageSize: 10,
      pageNum: 1,
      searchInput: "",
      title: "",
      successDrawer: false,
      tableData: [],
      successItems: [],
      totalTable: [],
      codeHeight: null,
      type: null,
      resultInfo: {},
      outsideItem: {},
      tableKey: null,
    };
  },
  computed: {
    pagedData() {
      const start = (this.pageNum - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.successItems.slice(start, end);
    },
    total() {
      return this.successItems.length;
    },
  },
  created() {},
  async mounted() {
    this.updata();
  },
  methods: {
    async handleConvert() {
      let { taskId, type, sourceDdl, sourceObjectName } = this.outsideItem;
      let res = await sqlTaskConvertSql({
        taskId,
        type,
        sourceDdl,
        sourceObjectName,
      });
      this.$message[res.data.code != 200 ? "error" : "success"](
        res.data.msg || res.data.message
      );
      if (res.data.code == 200 && res.data.data.length > 0) {
        this.outsideItem.sinkDdl = res.data.data;
      }
    },
    chatRepair(row) {
      // console.log();
      // const { id, taskId } = this.$route.query;
      // console.log(row);
      localStorage.setItem("migrationReportAi", JSON.stringify(row));
      this.$router.push({
        path: "/report/migrationReport/AI",
      });
    },
    updata() {
      const { id, taskId } = this.$route.query;
      // let res =
      Promise.all([
        getJobResult({
          id,
          taskId,
        }),
        getDataTaskconf({
          id: taskId,
        }),
      ]).then((res) => {
        this.resultInfo = {
          ...res[0].data,
          ...res[1].data,
          successRate: JSON.parse(res[0].data.taskResult).successRate,
        };
        this.tableData = JSON.parse(res[0].data.taskResult).data;
      });
    },
    executeSql() {
      let that = this;
      this.$modal
        .confirm("是否确认执行SQL？")
        .then(function () {
          return sqlTaskExecuteSql({
            datasourceId: that.resultInfo.sinkId,
            sqlContext: that.outsideItem.sinkDdl,
            databaseName: that.resultInfo.sinkName,
          });
        })
        .then((res) => {
          this.$message[res.data.code == 500 ? "error" : "success"](
            res.data.msg
          );
        });
    },
    handleFailInfo(item) {},
    async handleSuccess() {
      try {
        let res = await dataReportObjectEdit({
          id: this.outsideItem.id,
          code: 2,
          sinkDdl: this.outsideItem.sinkDdl,
        });
        this.$message.success(res.msg);
        this.updata();
        this.objDetailDrawer = false;
        this.successDrawer = false;
        this.tableKey = Math.random();
      } catch (error) {}
    },
    copyDdl(ddl) {
      const dom = document.createElement("input");
      dom.value = ddl;
      document.body.appendChild(dom);
      dom.select();
      document.execCommand("copy");
      document.body.removeChild(dom);
      this.$message.success("复制成功");
    },
    clickOpenObjDetail(row) {
      row.sourceDdl = this.sqlFormatter.format(row.sourceDdl || "");
      row.sinkDdl = this.sqlFormatter.format(row.sinkDdl || row.sourceDdl);
      // console.log(row);
      this.outsideItem = row;
      this.objDetailDrawer = true;
    },
    handleObjDetailClose() {
      this.objDetailDrawer = false;
    },
    handleSuccessCode(row) {
      this.successSql = row.sinkDdl;
      this.codeHeight =
        ((this.successSql.match(/\n/g) || []).length == 0
          ? 1
          : (this.successSql.match(/\n/g) || []).length) * 22;
    },
    editorInit() {
      // 初始化
      require("brace/ext/language_tools");
      require("brace/ext/beautify");
      require("brace/ext/error_marker");
      require("brace/ext/searchbox");
      require("brace/ext/split");
      require("brace/snippets/sql");
      require("brace/mode/sql");
      require("brace/theme/dracula");
    },
    searchSuccessTable() {
      this.pageNum = 1;
      if (this.searchInput.length == 0) {
        this.successItems = this.totalTable;
        return;
      }
      this.successItems = this.totalTable.filter((f) =>
        f.sourceObjectName.includes(this.searchInput)
      );
    },
    getIndex($index) {
      return (this.pageNum - 1) * this.pageSize + $index + 1;
    },
    handleClose(v) {
      this.successDrawer = false;
    },
    clickOpenSuccessDrawer(row, type) {
      this.pageNum = 1;
      this.type = type;
      this.successItems = !type ? row.successItems : row.failureItems;
      this.totalTable = !type ? row.successItems : row.failureItems;
      this.successDrawer = true;
      let titleName = this.dict.type.transfer_result_object_type.find(
        (f) => f.value == row.typeName
      ).label;
      this.title = `${titleName}迁移对象-${type ? "失败" : "成功"}列表`;
    },
    handleSizeChange(val) {},
    handleCurrentChange(val) {
      this.pageNum = val;
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 0;
  background-color: #fff;
  min-height: 100%;
  padding: 40px;
  min-width: 1285px;

  pre {
    height: 400px;
    overflow: auto;
    background-color: #282a36;
    color: #aaa;
    padding: 10px;
  }

  h3 {
    margin: 0;
    padding: 0;
    margin-bottom: 20px;
    font-size: 18px;
  }

  ul {
    display: flex;
    flex-wrap: wrap;
    list-style-type: none;
    justify-content: space-around;
    padding: 0;
    margin: 10px 0;
    // overflow: hidden;
    li {
      // display: flex;
      border: 1px solid #ccc;
      border-radius: 5px;
      margin: 0 10px 10px 0;
      padding: 15px;
      .title,
      .subTitle {
        display: flex;
        justify-content: space-between;
        align-items: baseline;
      }

      .title {
        span:nth-child(1) {
          font-size: 14px;
          color: #606266;
          font-weight: 600;
        }
        span:nth-child(2) {
          font-size: 14px;
          color: #606266;
        }
      }

      .subTitle {
        margin-top: 10px;
        span:nth-child(1) {
          color: #999;
          font-size: 14px;
          font-weight: 600;
        }
        span:nth-child(2) {
          color: #999;
          font-size: 14px;
          // font-weight: 600;
        }
      }
    }
  }

  .info {
    display: flex;
    width: 90%;
    justify-content: space-between;
    margin: 0 auto;
    padding: 0 15px;
    min-width: 1285px;

    .convert {
      display: flex;
      align-items: center;

      .convert-main {
        position: relative;

        span {
          position: absolute;
          font-size: 14px;
          top: 0px;
          left: 30px;
          font-weight: 600;
          color: #4d7df1;
          cursor: pointer;
        }
      }

      .icon-convert {
        cursor: pointer;
      }
    }

    .source,
    .sink {
      width: 45%;
      height: 100%;

      .sinkTable,
      .sourceTable {
        border: 1px solid #ccc;

        p {
          margin: 0;
          padding: 10px;
          color: #696969;
          font-size: 15px;
        }
        div {
          border-bottom: 1px solid #ccc;
          // border-bottom: none;
        }

        div:nth-child(3) {
          border-bottom: none;
          padding: 10px;
          width: 100%;
          display: flex;
          justify-content: right;
          align-items: center;
        }

        div {
          display: flex;
          align-items: baseline;

          p:nth-child(1) {
            width: 30%;
            // border-bottom: none;
          }
        }
      }
    }
  }

  .text {
    font-size: 14px;
    // cursor: pointer;
  }

  .successText {
    color: #67c23a;
    font-size: 16px;
    text-decoration: underline;
  }

  .successThanText {
    color: #c3b2b2;
    font-size: 16px;
    text-decoration: none;
    cursor: not-allowed;
  }

  .failThanText {
    color: #c3b2b2;
    font-size: 16px;
    text-decoration: none;
    cursor: not-allowed;
  }

  .failText {
    color: #fd4040;
    font-size: 16px;
    text-decoration: underline;
  }

  .tableBox {
    width: 90%;
    margin: 0 auto;
  }

  .paginationBox {
    margin-top: 10px;
    text-align: right;
  }

  .objName {
    color: #79c23a;
    font-size: 16px;
  }

  .failBadge {
    margin: 10px;

    ::v-deep .el-badge__content {
      font-size: 10px !important;
    }
  }

  .search {
    text-align: right;
    margin-bottom: 10px;
  }
}
.errTips {
  width: 100%;
  overflow: auto;
  background: #2a313d;
  color: #ccc;
  height: 100%;
}

.delStructure {
  margin-left: 9%;
}

.successRateText {
  font-size: 14px;
  color: #606266;
  font-weight: 600;
  margin-bottom: 10px;
}

::v-deep .el-progress-bar__innerText {
  // display: flex;
  // align-items: center;
  color: #fff !important;
}

::v-deep .is-fixed {
  top: 3px !important;
  right: 0px !important;
}
</style>
<style>
.popoverEditor {
  max-height: 600px !important;
  overflow-y: auto;
  overflow-x: hidden;
}
</style>
